/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-07-20 11:55:20
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-07-27 14:09:29
 * @FilePath: \ems_neutral_app\lib\pages\Login\RegisterPage.dart
 * @Description: 注册
 */
import 'package:ems_neutral_app/pages/Login/LoginGuidPage.dart';
import 'package:ems_neutral_app/pages/Mine/Language/LanguageController.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';

import '../../base/SilScaffold.dart';
import '../../bloc/userbloc/user_bloc.dart';
import '../../common/Method/CommonMethod.dart';
import '../../common/widgets/cubitWidget/BottomSheetView.dart';
import '../../common/widgets/cubitWidget/InputView.dart';
import '../../common/widgets/cubitWidget/SubmitBtn.dart';
import '../../config/AppInfo.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/router/ARouter.dart';
import '../Mine/AccountManager/ChooseCountryPage.dart';
import 'Controller/LoginController.dart';
import 'View/LoginRegisterItem.dart';
import 'View/LoginRichTextView.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  String? _countryName;
  String? _countryId;
  String? _email;
  String? _phone;
  String? _code;
  String? _password;
  String? _confirmPassword;
  bool _choosePhoneRegister = false; // 默认邮箱注册
  LoginController _loginController = Get.put(LoginController());
  LanguageController _languageController = LanguageController();
  bool _isPromptEnglish = true;

  /// 区号
  late String _areaCode;
  late List<String> _telCodeList;

  @override
  void initState() {
    super.initState();

    String? temp = UserBlocTool.userEntity?.areaCode;
    _areaCode = temp ?? '+86';
    _telCodeList = kTelCodeList;
    _isPromptEnglish = _languageController.isPromptEnglish();
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      sideMargin: 40.w,
      title: LangOf(context)?.register?.register,
      body: mainWidget(),
    );
  }

  mainWidget() {
    return Container(
        child: ListView(
      padding: EdgeInsets.symmetric(vertical: 40.w),
      children: [
        /// 选择注册方式，中文模式下才显示
        if (!_isPromptEnglish) chooseRegisterModeView(),

        /// 邮箱
        if (_choosePhoneRegister == false)
          LoginRegisterItem(
            imgPath: 'imgs/login/login_zh.png',
            hintText: LangOf(context)?.register?.emailPlaceholder,
            inputViewType: InputViewType.InputViewTypeEmail,
            codeType: CodeType.CodeTypeByEmail,
            onValid: (p0, p1) {
              _email = p1;
              setState(() {});
            },
          ),

        /// 手机
        if (_choosePhoneRegister) phoneInputView(),

        LoginRegisterItem(
          imgPath: 'imgs/login/login_yzm.png',
          hintText: LangOf(context)?.register?.codePlaceholder,
          inputViewType: InputViewType.InputViewTypeCode,
          account: _choosePhoneRegister ? _phone : _email,
          showSendCode: true,
          codeType: _choosePhoneRegister
              ? CodeType.CodeTypeByPhone
              : CodeType.CodeTypeByEmail,
          onValid: (p0, p1) {
            _code = p1;
          },
        ),
        LoginRegisterItem(
          imgPath: 'imgs/login/login_zh.png',
          hintText: LangOf(context)?.register?.passwordPlaceholder,
          inputViewType: InputViewType.InputViewTypePassword,
          onValid: (p0, p1) {
            _password = p1;
          },
        ),
        LoginRegisterItem(
          imgPath: 'imgs/login/login_zh.png',
          hintText: LangOf(context)?.register?.passwordPlaceholder_two,
          inputViewType: InputViewType.InputViewTypePassword,
          onValid: (p0, p1) {
            _confirmPassword = p1;
          },
        ),
        changeCountryWidget(),
        submitBtnWidget(),
        LoginRichTextView(
          leftTitle: LangOf(context)?.register?.haveAccount,
          rightTitle: LangOf(context)?.register?.goLogin,
          onTap: () => ARoute.gotoPage(context, LoginGuidPage()),
        )
      ],
    ));
  }

  /// 选择注册方式
  chooseRegisterModeView() {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SilButton(
            title: LangOf(context)?.register?.register_email,
            titleColor: _choosePhoneRegister
                ? ColorUtils.color_subtitle
                : ColorUtils.color_font_main,
            onTapFunc: () {
              if (_choosePhoneRegister != false) {
                _choosePhoneRegister = false;
                setState(() {});
              }
            },
          ),
          SilButton(
            title: LangOf(context)?.register?.register_phone,
            titleColor: _choosePhoneRegister
                ? ColorUtils.color_font_main
                : ColorUtils.color_subtitle,
            onTapFunc: () {
              if (_choosePhoneRegister != true) {
                _choosePhoneRegister = true;
                setState(() {});
              }
            },
          ),
        ],
      ),
    );
  }

  /// 选择所在的国家
  changeCountryWidget() {
    return SilEmptyButton(
      useConstrained: true,
      backgroundColor: ColorUtils.color_input_bg,
      margin: EdgeInsets.only(top: 30.w),
      radius: 5.w,
      padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
      child: Row(
        children: [
          SilImage(
            'imgs/personal/personal_dq.png',
            height: 28.w,
            width: 28.w,
            margin: EdgeInsets.only(right: 8.w),
          ),
          Container(
            height: 28.w,
            width: 0.5.w,
            margin: EdgeInsets.only(top: 3.w, bottom: 3.w, right: 18.w),
            color: ColorUtils.hexColor('#333333'),
          ),
          Expanded(
              child: SilText(
            _countryName ?? LangOf(context)?.selectGJ?.countryPhlace,
            color: ColorUtils.color_subtitle,
            fontSize: 14.sp,
          )),
          SilImage(
            'imgs/personal/personal_fh.png',
            height: 27.w,
            width: 27.w,
          )
        ],
      ),
      onTapFunc: () =>
          ARoute.gotoPage(context, ChooseCountryPage()).then((value) {
        if (value == null) {
          return;
        }

        if (!SilTools.stringIsEmpty(value.cnCountry) &&
            !SilTools.stringIsEmpty(value.enCountry)) {
          _countryName = _isPromptEnglish ? value.enCountry : value.cnCountry;
          _countryId = value.id;
          setState(() {});
        }
      }),
    );
  }

  submitBtnWidget() {
    return Container(
      alignment: Alignment.center,
      child: SubmitBtn(
        margin: EdgeInsets.only(top: 20.w),
        title: LangOf(context)?.register?.register,
        onTapFunc: () {
          // 隐藏键盘
          globalTextFieldDismiss(context);
          _loginController.register(
            context: context,
            phone: _phone,
            email: _email,
            code: _code,
            password: _password,
            confirmPassword: _confirmPassword,
            country: _countryName,
            areaCode: _countryId,
            phoneRegister: _choosePhoneRegister,
            successHandler: (p0) => ARoute.gotoPage(context, LoginGuidPage()),
          );
        },
      ),
    );
  }

  phoneInputView() {
    Widget letfWidget = Row(
      children: [
        SilImage(
          'imgs/login/login_sj.png',
          height: 28.w,
          width: 28.w,
          margin: EdgeInsets.only(right: 8.w),
        ),
        SilButton(
          padding: EdgeInsets.only(right: 5.w),
          imgPath: 'imgs/common/common_sanjx.png',
          imgHeight: 15.w,
          imgWidth: 15.w,
          title: _areaCode,
          titleColor: ColorUtils.color_font_main,
          fontSize: 14.sp,
          margin: EdgeInsets.only(right: 10.w),
          onTapFunc: showTelCodeListPop,
        ),
        Container(
          height: 28.w,
          width: 0.5.w,
          margin: EdgeInsets.only(top: 3.w, bottom: 3.w, right: 18.w),
          color: ColorUtils.hexColor('#333333'),
        ),
      ],
    );

    return InputView(
        margin: EdgeInsets.only(top: 30.w),
        inputViewMargin: EdgeInsets.symmetric(horizontal: 8.w),
        title: '',
        hintText: LangOf(context)?.register?.phonePlaceholder,
        inputViewType: InputViewType.InputViewTypePhone,
        leftView: letfWidget,
        hideTitle: true,
        onValid: (valid, value) {
          _phone = value;
          setState(() {});
        });
  }

  showTelCodeListPop() {
    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
          titles: _telCodeList,
          initialSelectedItem: _telCodeList.indexOf(_areaCode),
          tapSureSeletedFunc: (selected) {
            _areaCode = _telCodeList[selected];
            setState(() {});
          },
        ));
  }
}
